/**
 * 
 */
package jpb.process;

import jpb.Assert;

import java.util.concurrent.Callable;

/**
 * A {@link Callable} implementation that waits for
 * provided {@link Process} instance to finish
 * and returns the process' exit value. May be
 * used to perform timed waits on sub-processes
 * to finish, since the {@link Process} API provides
 * only non-timed wait functionality. 
 * 
 * @author Dariusz Kordonski
 */
public class ProcessWaiter implements Callable<Integer> {

    private final Process process;
    private final ProcessOutputDrainer outputDrainer;

    public ProcessWaiter(Process process) {
        this(process, null);
    }

    public ProcessWaiter(Process process, ProcessOutputDrainer drainer) {
        this.process = Assert.notNull("process", process);
        this.outputDrainer = drainer;
    }

    @Override
    public Integer call() throws Exception {
        final int result = process.waitFor();
        if (outputDrainer != null) {
            outputDrainer.stop();
        }
        return result;
    }
    
}
